package com.team.easybuy.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.jcraft.jsch.SftpException;
import com.team.easybuy.entity.Car;
import com.team.easybuy.entity.OrderDetail;
import com.team.easybuy.entity.Product;
import com.team.easybuy.mapper.ProductMapper;
import com.team.easybuy.service.ProductService;
import com.team.easybuy.util.SftpUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private SolrClient solrClient;

    @Override
    public Product selectById(Integer id) {
        return productMapper.selectById(id);
    }

    @Override
    public List<Product> selectByCId(Integer id) {
        return productMapper.selectByCId(id);
    }

    @Override
    public PageInfo<Product> solrById(@RequestParam Map<String, Object> params) {
        String id = params.get("id").toString();
        String str = "cate1Id_i:" + id + " OR cate2Id_i:" + id + " OR cate3Id_i:" + id;
        SolrQuery query = new SolrQuery();
        query.setQuery(str);
        try {
            query.setRows(Integer.MAX_VALUE);
            query.setSort("id", SolrQuery.ORDER.desc);
            QueryResponse response = solrClient.query(query);
            List<Product> list = response.getBeans(Product.class);
            int pageNum = Integer.parseInt(params.get("pageNum").toString());
            int pageSize = Integer.parseInt(params.get("pageSize").toString());
            Page<Product> page = new Page<>(pageNum, pageSize);
            //为Page类中的total属性赋值
            int total = list.size();
            page.setTotal(total);
            //计算当前需要显示的数据下标起始值
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, total);
            //从链表中截取需要显示的子链表，并加入到Page
            page.addAll(list.subList(startIndex, endIndex));
            //以Page创建PageInfo
            PageInfo<Product> pageInfo = new PageInfo<>(page);
            return pageInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public PageInfo<Product> solrByName(@RequestParam Map<String, Object> params) {
        String name = params.get("name").toString();
        String str = "name_ik:" + name + " OR des_ik:" + name;
        SolrQuery query = new SolrQuery();
        if (!name.equals("")) {
            query.setQuery(str);
        } else {
            query.setQuery("*:*");
        }
        try {
            query.setRows(Integer.MAX_VALUE);
            query.setSort("id", SolrQuery.ORDER.desc);
            QueryResponse response = solrClient.query(query);
            List<Product> list = response.getBeans(Product.class);
            int pageNum = Integer.parseInt(params.get("pageNum").toString());
            int pageSize = Integer.parseInt(params.get("pageSize").toString());
            Page<Product> page = new Page<>(pageNum, pageSize);
            //为Page类中的total属性赋值
            int total = list.size();
            page.setTotal(total);
            //计算当前需要显示的数据下标起始值
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, total);
            //从链表中截取需要显示的子链表，并加入到Page
            page.addAll(list.subList(startIndex, endIndex));
            //以Page创建PageInfo
            PageInfo<Product> pageInfo = new PageInfo<>(page);
            return pageInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Product> solrByCId123(Integer id) {
        return productMapper.selectByCId123(id);
    }

    @Override
    public boolean addPro(Product product, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(fileName);
        String newFileName = UUID.randomUUID() + "." + extension;
        product.setFileName(newFileName);
        product.setIsDelete(0);
        SftpUtil util = new SftpUtil("zl", "123456", "192.168.189.129", 22);
        util.login();
        try {
            InputStream is = file.getInputStream();
            util.upload("/home/zl/image", newFileName, is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            util.logout();
        }
        if (productMapper.addOne(product) > 0) {
            try {
                solrClient.addBean(product);
                solrClient.commit();
            } catch (Exception e) {
                try {
                    solrClient.rollback();
                } catch (Exception Exception) {
                    Exception.printStackTrace();
                }
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean delPro(Integer id) {
        Product product = productMapper.selectById(id);
        SftpUtil util = new SftpUtil("zl", "123456", "192.168.189.129", 22);
        util.login();
        try {
            util.delete("/home/zl/image", product.getFileName());
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            util.logout();
        }
        if (productMapper.deleteById(id) > 0) {
            try {
                solrClient.deleteById(id.toString());
                solrClient.commit();
            } catch (Exception e) {
                try {
                    solrClient.rollback();
                } catch (Exception Exception) {
                    Exception.printStackTrace();
                }
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean editProNoFile(Product product) {
        if (productMapper.updateByPro(product) > 0) {
            try {
                solrClient.addBean(product);
                solrClient.commit();
            } catch (Exception e) {
                try {
                    solrClient.rollback();
                } catch (Exception Exception) {
                    Exception.printStackTrace();
                }
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean editProHasFile(Product product, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(fileName);
        String newFileName = UUID.randomUUID() + "." + extension;
        SftpUtil util = new SftpUtil("zl", "123456", "192.168.189.129", 22);
        util.login();
        try {
            InputStream is = file.getInputStream();
            util.upload("/home/zl/image", newFileName, is);
            util.delete("/home/zl/image", product.getFileName());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            util.logout();
        }
        product.setFileName(newFileName);
        if (productMapper.updateByPro(product) > 0) {
            try {
                solrClient.addBean(product);
                solrClient.commit();
            } catch (Exception e) {
                try {
                    solrClient.rollback();
                } catch (Exception Exception) {
                    Exception.printStackTrace();
                }
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean updateStock(List<Car> carList) {
        boolean flag = true;
        for (Car car : carList) {
            if (productMapper.updateStock(car.getpId(), car.getpCount()) < 0) {
                flag = false;
            }
        }
        return flag;
    }

    @Override
    public void updateAddStock(List<OrderDetail> detailList) {
        for (OrderDetail detail : detailList) {
            productMapper.updateAddStock(detail.getProductId(), detail.getQuantity());
        }
    }

    @Override
    public boolean checkNum(List<Car> carList) {
        for (Car car : carList) {
            if (car.getpCount() > productMapper.selectStock(car.getpId())) {
                return false;
            }
        }
        return true;
    }
}
